<template>
  <div id="scriptExecution">
    <ReturnPage />
    <div class="mt20">
      <el-button type="primary" size="mini" @click="dialogVisible = true"
        >添加脚本</el-button
      >
      <!-- 脚本列表 -->
      <div class="tp_box mt20">
        <el-table
          height="calc(100vh - 280px)"
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            prop="name"
            label="脚本名称"
            show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="命令"
            show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="type" label="类型">
            <template slot-scope="scope">
              <el-tag type="success">{{ scope.row.type | getType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型">
            <template slot-scope="scope">
              <el-button type="primary" @click="showEditScript(scope.row)"
                >编辑</el-button
              >
              <el-button type="danger" @click="delScript(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="tableData.length > 0"
          :total="total"
          :page.sync="query.pageNum"
          :limit.sync="query.pageSize"
          @pagination="getListData"
        />
      </div>

      <!-- 脚本执行弹窗 -->
      <el-dialog
        :title="ruleForm.id ? '编辑脚本' : '新增脚本'"
        :visible.sync="dialogVisible"
        @open="openDialog"
        @close="closeDialog('ruleForm')"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          size="mini"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="脚本名称" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入脚本名称(仅支持英文+特殊字符)"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="主机群组" prop="groupid">
            <el-select
              v-model="ruleForm.groupid"
              placeholder="请选择主机群组"
              style="width: 300px"
            >
              <el-option
                :label="item.name"
                :value="item.groupid"
                v-for="item in hostGroup"
                :key="item.groupid"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="脚本来源" prop="source">
            <el-radio-group v-model="ruleForm.source" @change="showMonaco">
              <el-radio :label="1">手工输入</el-radio>
              <el-radio :label="2">脚本仓库</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <!-- <el-form-item
            label="脚本仓库"
            prop="scriptid"
            v-if="ruleForm.source == 2"
          >
            <el-select
              v-model="ruleForm.scriptid"
              placeholder="请选择脚本仓库"
              style="width: 300px"
            >
              <el-option
                :label="item.name"
                :value="item.scriptid"
                v-for="(item, index) in tableData"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="作用域" prop="scope">
            <el-radio-group v-model="ruleForm.scope">
              <el-radio :label="1">故障自愈</el-radio>
              <el-radio :label="2">主机执行</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="ruleForm.type">
              <el-radio :label="0">脚本</el-radio>
              <el-radio :label="2">SSH</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- <el-form-item label="用户名" prop="username" v-if="ruleForm.type">
            <el-input
              v-model="ruleForm.username"
              placeholder="请输入用户名"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="ruleForm.type">
            <el-input
              v-model="ruleForm.password"
              placeholder="请输入密码"
              style="width: 300px"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item label="端口" prop="port" v-if="ruleForm.type">
            <el-input
              v-model="ruleForm.port"
              placeholder="请输入端口"
              style="width: 300px"
            ></el-input>
          </el-form-item>
 -->
          <el-form-item label="脚本内容" prop="content">
            <div id="editorJson" class="json-editor" />
          </el-form-item>
          <el-form-item label="超时" prop="timeout">
            <el-input
              v-model="ruleForm.timeout"
              style="width: 300px"
              placeholder="单位：s"
            ></el-input>
          </el-form-item>
          <el-form-item label="执行原因" prop="description">
            <el-input
              v-model="ruleForm.description"
              style="width: 300px"
              placeholder="请输入执行原因"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              ruleForm.id ? "提交修改" : "新增脚本"
            }}</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
//接口
import {
  getScriptList_Api, //脚本列表
  addScript_Api, //新增脚本
  delScript_Api, //删除脚本
  editScript_Api, //编辑脚本
} from "@/api/automated/script.js";

//代码编辑器
import { beautifierConf } from "@/utils/index";
import loadMonaco from "@/utils/loadMonaco";
import loadBeautifier from "@/utils/loadBeautifier";
let beautifier;
let monaco;
export default {
  data() {
    return {
      //分页
      query: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      //表单
      ruleForm: {
        name: null, //脚本名称
        scope: 1, //作用域
        content: null, //内容
        type: 0, //来源
        description: null, //描述
        timeout: null, //超时
        // username: null, //用户名
        // password: null, //密码
        // post: null, //端口
      },
      //表单验证规则
      rules: {
        name: [{ required: true, message: "请输入脚本名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        content: [
          { required: true, message: "请输入脚本内容", trigger: "change" },
        ],
        timeout: [
          { required: true, message: "请输入超时时间", trigger: "change" },
        ],
        scope: [{ required: true, message: "请选择作用域", trigger: "change" }],
      },
      jsonEditor: null, //编辑器对象
      dialogVisible: false, //控制脚本执行弹框
      //列表数据
      tableData: [],
      //主机群组
      hostGroup: [],
    };
  },
  created() {
    // this.getHostGroup(); //获取主机群组
    this.getListData(); //获取脚本列表
  },
  methods: {
    //获取脚本列表数据
    getListData() {
      getScriptList_Api(this.query).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
      });
    },
    //获取主机群组
    /* getHostGroup() {
      getHostListGroup_Api().then((res) => {
        this.hostGroup = res.data;
      });
    }, */
    //提交
    submitForm(formName) {
      const tempObj = this.deleteObjectItem(this.ruleForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //根据是否有id判断
          if (tempObj.id) {
            //编辑脚本
            editScript_Api(tempObj).then((res) => {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.getListData();
            });
          } else {
            //新增脚本
            addScript_Api(tempObj).then((res) => {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.getListData();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除脚本
    delScript(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          delScript_Api(id)
            .then((res) => {
              this.getListData();
              this.$message.success("删除成功");
            })
            .catch((error) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //显示编辑脚本
    showEditScript(row) {
      this.ruleForm = { ...row };
      this.dialogVisible = true;
    },

    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //格式化代码
    onOpen() {
      loadBeautifier((btf) => {
        beautifier = btf;
        this.beautifierJson = beautifier.js(
          this.ruleForm.content,
          beautifierConf.js
        );

        loadMonaco((val) => {
          monaco = val;
          this.setEditorValue("editorJson", this.beautifierJson);
        });
      });
    },
    //打开弹窗时，调用创建编辑器的方法
    openDialog() {
      this.$nextTick(() => {
        this.onOpen(); //创建编辑器
      });
    },
    //关闭弹窗
    closeDialog(formName) {
      this.ruleForm = {
        name: null, //脚本名称
        content: null, //内容
        type: 0, //来源
        scope: 1, //来源
        description: null, //描述
        timeout: null, //超时
        username: null, //用户名
        password: null, //密码
        post: null, //端口
      };
      this.$refs[formName].resetFields();
    },
    //创建编辑器对象
    setEditorValue(id, codeStr) {
      const editorJson = document.getElementById(id);
      if (this.jsonEditor) {
        this.jsonEditor.setValue(codeStr);
      } else {
        this.jsonEditor = monaco.editor.create(editorJson, {
          value: codeStr,
          theme: "vs-dark",
          language: "java",
          automaticLayout: true,
        });
      }

      this.jsonEditor.onDidChangeModelContent((event) => {
        this.ruleForm.content = this.jsonEditor.getValue();
      });
    },
    //切换脚本来源时显示Monaco
    /*  showMonaco() {
      if (this.ruleForm.source == 1) {
        this.onOpen();
      } else this.jsonEditor = null;
    }, */
    //提交表单之前，删除不需要的项
    deleteObjectItem({ ...object }) {
      if (object.type == 0) {
        //手工输入
        //类型为脚本
        // delete object.username;
        // delete object.password;
        // delete object.port;
        // delete object.scriptid;
      } else if (object.type == 2) {
        //手工输入
        //类型为ssh
        // delete object.scriptid;
      }
      /* else if (object.source == 2) {
        //类型为脚本仓库
        delete object.username;
        delete object.password;
        delete object.port;
        // delete object.type;
        delete object.command;
      } */
      return object;
    },
  },
  mounted() {},
  filters: {
    //格式化脚本类型
    getType(val) {
      switch (val) {
        case 0:
          return "脚本";
        case 1:
          return "IPMI";
        case 2:
          return "SSH";
        case 3:
          return "Telnet";
        default:
          return "WebHook";
      }
    },
    //根据groupid找出主机群组名称
    getHostGroupNameByid(val, hostGroup) {
      return hostGroup.find((item) => item.groupid == val)?.name;
    },
  },
};
</script>

<style lang="scss" scoped>
.json-editor {
  border: 1px solid #d3d3d3;
  border-radius: 5px;
  overflow: hidden;
  height: 260px;
}
</style>